<?php
namespace Controller;
use Kuyuan\WqCore\controller\Controller;
use Kuyuan\WqCore\util\DB;
use Model\RedModel;
use Model\RedRecordModel;

/**
 * 红包
 * Class Red
 * @package Controller
 */
class Red extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 发布红包
     * @param array $_data 红包数据
     * @param int $_uid 用户id
     * @return mixed
     */
    public function add(Array $_data, $_uid = 0)
    {
        if (!$_uid) $_uid = $this->_uid;
        $_data["uid"] = $_uid;
        $_data["uniacid"] = $this->_uniacid;
        return RedModel::createId($_data);
    }

    /**
     * 修改红包
     * @param $_red_id
     * @param $_data
     * @return mixed
     */
    public function edit($_red_id, $_data)
    {
        return RedModel::where("id", $_red_id)->update($_data);
    }

    /**
     * 通过红包id获取指定一个字段的值
     * @param $_red_id
     * @param $_field
     * @return mixed
     */
    public function value($_red_id, $_field)
    {
        return RedModel::where("id", $_red_id)
            ->value($_field);
    }

    /**
     * 获取指定用户红包列表
     * @param array $_limit
     * @param int $_uid
     * @param int $_enter_red_id
     * @return mixed
     */
    public function getUserList(Array $_limit, $_enter_red_id = 0,$_uid = 0)
    {
        if (!$_uid) $_uid = $this->_uid;
        return RedModel::where("uid", $_uid)
            ->where("status", ">=", 2)
            ->where("status", "<", 6)
            ->field(array("id", "uid", "red_type", "number", "numbered", "title", "media", "status","area","area_type","time_type","start_time","end_time","question","answer","red_form","red_form_id"))
            ->limit($_limit[0], $_limit[1])
            ->order("id = ".$_enter_red_id,"desc")
            ->order("number != numbered","desc")
            ->order("id", "desc")
            ->noGetAttr("media")
            ->cache(!KUYUAN_DEBUG)
            ->select();
    }

    /**
     *获取首页红包列表
     * @param array $_limit
     * @param string $_area
     * @param int $_enter_red 入口红包id
     * @return array
     */
    public function getHomeList(Array $_limit, $_area,$_enter_red = 0)
    {
        $_sql = "
            SELECT
                a.id,
                a.uid,
                a.media,
                a.red_type,
                a.area_type,
                a.area,
                a.number,
                a.numbered,
                a.title,
                a.start_time,
                a.end_time,
                a.question,
                a.answer,
                a.time_type,
                a.area_type,
                a.area,
                a.link,
                a.red_form,
                a.red_form_id
            FROM
                " . DB::tableName("red") . " AS a
            WHERE
                a.uniacid = " . $this->_uniacid . "
            AND
                (a.status = 2
            AND
                a.id != :red_id
            AND
                a.`number` > a.`numbered` 
            AND
                    (
                        a.`area_type` = 0
                      OR
                        LEFT(:area,CHAR_LENGTH(a.`area`)) = a.`area`
                    )
                )
            OR
                (
                    (SELECT id FROM " . DB::tableName('red_record') . " WHERE pid = 0 AND red_id = a.id AND uid = {$this->_uid} LIMIT 1)
                AND
                    status != 9    
                )
            ORDER BY 
                (SELECT id FROM " . DB::tableName('red_record') . " WHERE pid = 0 AND red_id = a.id AND uid = {$this->_uid} LIMIT 1) ASC,           
                a.id DESC
            LIMIT
                " . $_limit[0] . "," . $_limit[1] . "
        ";
        return RedModel::sql($_sql)
            ->bind(array("red_id" => $_enter_red,"area"=>$_area))
            ->cache(!KUYUAN_DEBUG)
            ->fetchAll();
    }

    /**
     * 首页红包列表获取一个红包详情
     * @param $_red_id
     * @return mixed
     */
    public function getHomeOne($_red_id)
    {
        return RedModel::where("id", $_red_id)
            ->field(array(
                    "id",
                    "uid",
                    "red_type",
                    "money",
                    "pay",
                    "charge",
                    "pay_type",
                    "type",
                    "send_coupon",
                    "coupon",
                    "red_form",
                    "red_form_id",
                    "number",
                    "title",
                    "media",
                    "question",
                    "answer",
                    "award",
                    "time_type",
                    "start_time",
                    "end_time",
                    "area_type",
                    "area",
                    "link",
                    "create_time",
                    "status"))
            ->cache(!KUYUAN_DEBUG)
            ->find();
    }

    /**
     * 获取一个红包数据
     * @param $_red_id
     * @return mixed
     */
    public function get($_red_id)
    {
        return RedModel::where("id", $_red_id)
            ->field(array(
                "id",
                "uid",
                "red_type",
                "money",
                "pay",
                "charge",
                "pay_type",
                "type",
                "send_coupon",
                "coupon",
                "red_form",
                "red_form_id",
                "number",
                "numbered",
                "title",
                "media",
                "question",
                "answer",
                "award",
                "time_type",
                "start_time",
                "end_time",
                "area_type",
                "area",
                "link",
                "create_time",
                "status"))
            ->noGetAttr("title")
            ->cache(!KUYUAN_DEBUG)
            ->find();
    }

    /**
     * 获取首页红包列表可开红包总数
     * @return mixed
     */
    public function getHomeListTotal()
    {
        $_sql = "
            SELECT
                COUNT(`id`)
            FROM
                " . DB::tableName("red") . "
            WHERE
                uniacid = " . $this->_uniacid . "
        ";
        return RedModel::sql($_sql)
            ->cache(!KUYUAN_DEBUG)
            ->column();
    }

    /**
     * 获取一个红包详情
     * @param int $_red_id 红包id
     * @return mixed
     */
    public function find($_red_id)
    {
        return RedModel::where("id", $_red_id)
            ->field(array(
                    "id",
                    "uid",
                    "red_type",
                    "money",
                    "pay",
                    "charge",
                    "pay_type",
                    "type",
                    "send_coupon",
                    "coupon",
                    "number",
                    "numbered",
                    "title",
                    "media",
                    "question",
                    "answer",
                    "award",
                    "time_type",
                    "start_time",
                    "end_time",
                    "area_type",
                    "area",
                    "link",
                    "create_time",
                    "status")
            )
            ->NoGetAttr("cover,owner_header")
            ->cache(!KUYUAN_DEBUG)
            ->find();
    }

    /**
     * 获取一个红包详情,不做任何getAttr处理
     * @param int $_red_id 红包id
     * @return mixed
     */
    public function take($_red_id)
    {
        return RedModel::where("id", $_red_id)
            ->field(array(
                    "id",
                    "uid",
                    "red_type",
                    "money",
                    "pay",
                    "charge",
                    "pay_type",
                    "type",
                    "send_coupon",
                    "coupon",
                    "number",
                    "numbered",
                    "title",
                    "media",
                    "question",
                    "answer",
                    "award",
                    "time_type",
                    "start_time",
                    "end_time",
                    "area_type",
                    "area",
                    "link",
                    "create_time",
                    "status")
            )
            ->NoGetAttr(false)
            ->cache(!KUYUAN_DEBUG)
            ->find();
    }

    /**
     * 新增红包开启数量
     * @param $_red_id
     */
    public function addNumbered($_red_id)
    {
        RedModel::where("id", $_red_id)
            ->addition("numbered");
    }

    /**
     * 获取随机红包剩余金额
     * @param int $_red_id 红包id
     * @return mixed
     */
    function surplus($_red_id)
    {
        $_already_money = RedRecordModel::where("red_id", $_red_id)
            ->sum("money");
        $_total_money = RedModel::where("id", $_red_id)
            ->value("money");
        return $_total_money - $_already_money;
    }

    /**
     * 获取红包已发数量
     * @param int $_red_id
     * @return int
     */
    public function numbered($_red_id)
    {
        return RedModel::where("id", $_red_id)
            ->value("numbered");
    }

    /**
     * 获取红包分享参数
     * @param $_red_id
     * @return mixed
     */
    public function findShareParam($_red_id)
    {
        return RedModel::field(array("id", "title", "uid", "media", "red_type"))
            ->where("id", $_red_id)
            ->noGetAttr(
                "owner_header,video,images,link,media,choice_question,answer_question,time"
            )
            ->cache(!KUYUAN_DEBUG)
            ->find();
    }

    /**
     * 获取一个用户发红包的总金额
     * @param int $_uid
     * @return float
     */
    public function findSendMoney($_uid = 0)
    {
        if(!$_uid) $_uid = $this->_uid;
        // 获取随机红包总金额
        $_money = RedModel::where("uid",$_uid)
            ->where("type",2)
            ->sum("money");
        // 获取普通红包总金额
        $_sql = "SELECT
                    SUM(money*number)
                 FROM
                    ".DB::tableName("red")."
                 WHERE
                    uid = :uid
                 AND
                    type = 1
                 AND
                    (status = 2
                 OR
                    status = 4)
                 LIMIT
                    1
                 ";
        $_money += RedModel::sql($_sql)
            ->bind(array("uid"=>$_uid))
            ->cache(!KUYUAN_DEBUG)
            ->column();
        return sprintf("%1\$.2f", $_money);
    }

    /**
     * 获取指定用户发红包的数量
     * @param int $_uid
     * @return mixed
     */
    public function findUserNumber($_uid = 0)
    {
        if(!$_uid) $_uid = $this->_uid;
        return RedModel::where("uid",$_uid)
            ->where("status = 2 OR status = 4")
            ->count();
    }

    /**
     * 获取红包二维码
     * @param int $_red_id
     * @param string $_url
     * @return mixed
     */
    public function getRedQrcode($_red_id,$_url)
    {
        return $this->getQrcode("red_qrcode",$_red_id,$_url);
    }

    /**
     * 获取红包总数
     */
    public function getTotal()
    {
        return RedModel::where("uniacid",$this->_uniacid)
            ->where("status","!=",1)
            ->where("status","!=",6)
            ->where("status","!=",8)
            ->count();
    }

    /**
     * 获取指定日期的红包数量
     * @param string $_date 日期 格式 2020-10-29
     * @return mixed
     */
    public function getDayTotal($_date = "")
    {
        if(empty($_date)) {
            $_start_time = strtotime(date("Y-m-d",TIMESTAMP));
            $_end_time = $_start_time + 86400;
        } else {
            $_start_time = strtotime($_date);
            $_end_time = $_start_time + 86400;
        }
        return RedModel::where("uniacid",$this->_uniacid)
            ->where("status","!=",1)
            ->where("status","!=",6)
            ->where("status","!=",8)
            ->where("create_time",">=",$_start_time)
            ->where("create_time","<",$_end_time)
            ->count();
    }

    /**
     * 获取系统总收入
     */
    public function getSystemIncome()
    {
        return RedModel::where("uniacid",$this->_uniacid)
            ->where("status","!=",1)
            ->where("status","!=",6)
            ->where("status","!=",8)
            ->sum("charge");
    }

    /**
     * 获取系统指定日期的收入
     * @param string $_date 日期 格式2020-10-23
     * @return mixed
     */
    public function getSystemDayIncome($_date = "")
    {
        if(empty($_date)) {
            $_start_time = strtotime(date("Y-m-d",TIMESTAMP));
            $_end_time = $_start_time + 86400;
        } else {
            $_start_time = strtotime($_date);
            $_end_time = $_start_time + 86400;
        }
        return RedModel::where("uniacid",$this->_uniacid)
            ->where("status","!=",1)
            ->where("status","!=",6)
            ->where("status","!=",8)
            ->where("create_time",">=",$_start_time)
            ->where("create_time","<",$_end_time)
            ->sum("charge");
    }

    /**
     * 后台管理红包列表
     * @param array $_limit
     * @return RedModel
     */
    public function getManageList(Array $_limit)
    {
        return RedModel::where("uniacid",$this->_uniacid)
            ->where("status","!=",1)
            ->where("status","!=",6)
            ->where("status","!=",8)
            ->where("status","!=",9)
            ->order("status","desc")
            ->order("id","desc")
            ->limit($_limit[0],$_limit[1])
            ->noGetAttr('under,submit_form')
            ->select();
    }

    /**
     * 获取后台红包列表总数
     */
    public function getManageTotal()
    {
        return RedModel::where("uniacid",$this->_uniacid)
            ->where("status","!=",1)
            ->where("status","!=",6)
            ->where("status","!=",8)
            ->where("status","!=",9)
            ->count();
    }

    /**
     * 获取指定红包余额
     * @param $_red_id
     * @return double 返回红包余额
     */
    public function getRedBalance($_red_id)
    {
        $_red = $this->take($_red_id);
        if($_red["type"] == 1) {
            // 普通红包
            $_surplus_number = $_red["number"] - $_red["numbered"];
            $_balance = $_surplus_number * $_red["money"];
        } else {
            // 手气红包
            $_balance = $this->surplus($_red_id);
        }
        return $_balance;
    }

    /**
     * 数据自增
     * @param int $_red_id 红包id
     * @param string $_field 字段
     * @param int $_value 新增的数量
     * @return mixed
     */
    public function addition($_red_id,$_field,$_value = 1)
    {
        return RedModel::where("id",$_red_id)->addition($_field,$_value);
    }
}